package cn.hdu.liang.ch6;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.Phaser;

public class PhaserDemo {
    public static void main(String[] args) {
        List<Runnable> tasks = new ArrayList<>();
        tasks.add(() -> System.out.printf("%s 运行 %d%n",
                Thread.currentThread().getName(), System.currentTimeMillis()));

        tasks.add(() -> System.out.printf("%s 运行 %d%n",
                Thread.currentThread().getName(), System.currentTimeMillis()));
        runTasks(tasks);
    }

    private static void runTasks(List<Runnable> tasks) {
        final Phaser phaser = new Phaser(1);
        for(final Runnable task : tasks) {
            phaser.register();
            Runnable r = () -> {
                try {
                    Thread.sleep(500 + new Random().nextInt(1000));
                } catch(InterruptedException ie) {
                    System.out.println("打断线程");
                }
                phaser.arriveAndAwaitAdvance();
                task.run();
            };

            Executors.newSingleThreadExecutor().execute(r);
        }
        phaser.arriveAndDeregister();
    }
}
